<template>
	<view>
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">加油记录</block>
			<block slot="right">
				<u-icon name="scan" color="#FFF" size="44" style="padding-right: 20rpx;" @click="scanQrCode"></u-icon>
			</block>
		</cu-custom>
		<view class="wrap">
			<u-form :model="oilRecord" ref="oilRecordForm" label-width="130" :rules="oilRecordRules">
				<view class="info-panel">基本信息</view>
				<u-form-item label="单位" prop="orgName">
					<u-input type="select" v-model="oilRecord.orgName" placeholder="请选择用油单位"
						@click="pickerCompanyShow=true">
					</u-input>
					<u-select :list="companyList" v-model="pickerCompanyShow" @confirm="onCompanySelected"></u-select>
				</u-form-item>
				<u-form-item label="车辆" prop="deviceName">
					<u-input type="select" v-model="oilRecord.deviceName" placeholder="请选择用油设备"
						@click="pickerDeviceShow=true">
					</u-input>
					<u-select :list="oilDeviceList" v-model="pickerDeviceShow" @confirm="onDeviceSelected"></u-select>
				</u-form-item>

				<u-form-item label="表计类型">
					<u-radio-group :disabled="!oilRecord.deviceId" v-model="oilInfo.meterType">
						<u-radio v-for="(item, index) in meterTypeList" :key="item.id" :name="item.name">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<view v-if="oilInfo.meterType==='里程表'">
					<!-- <u-form-item label="上次里程">
						<u-input type="text" disabled v-model="lastOilRecord.odoTableValue"
							placeholder="选择车辆自动补全(首次为0)">
						</u-input>
					</u-form-item> -->

					<u-form-item label="本次里程" prop="odoTableValue">
						<u-input type="text" v-model="oilRecord.odoTableValue" placeholder="请填写本次加油时里程表数值">
						</u-input>
					</u-form-item>
				</view>
				<view v-if="oilInfo.meterType==='台时表'">
					<!-- <u-form-item label="上次台时">
						<u-input type="text" disabled v-model="lastOilRecord.ohcTableValue"
							placeholder="选择车辆自动补全(首次为0)">
						</u-input>
					</u-form-item> -->

					<u-form-item label="本次台时" prop="ohcTableValue">
						<u-input type="text" v-model="oilRecord.ohcTableValue" placeholder="请填写本次加油时台时表数值">
						</u-input>
					</u-form-item>
				</view>
				<!-- 加油记录信息-->
				<view class="info-panel">加油信息</view>
				<u-form-item label="燃油类型" prop="measurePointId">
					<u-input type="text" v-if="false" v-model="oilRecord.measurePointId">
					</u-input>
					<u-radio-group :disabled="!oilRecord.deviceId" v-model="oilInfo.oilType">
						<u-radio @change="onSelectOilType" v-for="(item, index) in oilTypeList" :key="item.id"
							:name="item.name">
							{{item.name}}
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<view v-if="oilRecord.measurePointId">
					<u-form-item label="油品" prop="oilSubType">
						<u-input type="text" v-if="false" v-model="oilRecord.oilSubType">
						</u-input>
						<u-radio-group v-model="oilInfo.oilSubType">
							<u-radio @change="onSelectOilSubType" v-for="(item, index) in oilSubTypeList" :key="item.id"
								:name="item.name">
								{{item.name}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</view>
				<u-form-item label="加油时间" prop="recordTime">
					<u-input type="select" @click="oilDatePickerShow = true" v-model="oilRecord.recordTime">
					</u-input>
					<u-picker v-model="oilDatePickerShow" mode="time" :params="dateTimePara"
						@confirm="onConfirmOilDate"></u-picker>
				</u-form-item>
				<u-form-item label="油价(元)" prop="oilPrice">
					<u-input v-model="oilRecord.oilPrice" placeholder="请填写油价" style="color: #007AFF;font-weight: 600;">
					</u-input>
				</u-form-item>
				<u-form-item label="油量(升)" prop="oilValue">
					<u-input v-model="oilRecord.oilValue" placeholder="请填写加油量" style="color:#007AFF;font-weight: 600;">
					</u-input>
				</u-form-item>
				<view class="info-panel">人员信息</view>
				<u-form-item label="加油人" prop="recordComments">
					<u-input type="text" v-model="oilRecord.recordComments" placeholder="请填写加油人员工号">
					</u-input>
				</u-form-item>
				<u-form-item label="授权码" prop="userConfirmPwd">
					<u-input type="password" v-model="oilRecord.userConfirmPwd" placeholder="请填写加油人授权码">
					</u-input>
				</u-form-item>
				<u-form-item label="操作员" prop="submitter">
					<u-input type="text" v-model="oilRecord.submitter" placeholder="请填写操作员工号">
					</u-input>
				</u-form-item>
				<u-form-item label="密码" prop="submitterPassword">
					<u-input type="password" v-model="oilRecord.submitterPassword" placeholder="请填写操作员操作密码">
					</u-input>
				</u-form-item>
			</u-form>
		</view>
		<view style="height: 100rpx;"></view>
		<view class="cu-bar tabbar bg-white shadow foot">
			<u-button type="primary" style="width: 80%;margin: 20rpx auto;" @click="saveOilRecrod()">提交加油记录</u-button>
		</view>
	</view>
</template>

<script>
	import {
		bookSave,
		checkOilMeasurePoint,
		loadOilDeviceList,
		loadDeviceCompanyList,
		saveOilRecordData,
		checkUserAuth,
		getDeviceInfo
	} from '@/api/book/book.js';
	import {
		sha1
	} from '@/common/sha1.js';

	import {
		hex_md5
	} from '@/common/md5.min.js';
	import {
		currentUserInfo
	} from '@/api/index/index.js';

	export default {
		data() {
			return {
				oilInfo: {
					oilType: null,
					oilSubType: null,
					meterType: '里程表'
				},
				dateTimePara: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true
				},
				companyList: [],
				oilDeviceList: [],
				oilTypeList: [{
					id: 2001,
					name: '柴油'
				}, {
					id: 2002,
					name: '汽油'
				}],
				meterTypeList: [{
					id: 1,
					name: '里程表'
				}, {
					id: 2,
					name: '台时表'
				}],
				actionSheetShow: false,
				pickerCompanyShow: false,
				pickerDeviceShow: false,
				selectShow: false,
				oilDatePickerShow: false,
				lastOilRecord: {
					odoTableValue: null,
					ohcTableValue: null
				},
				oilRecord: {
					orgId: null,
					orgName: null,
					deviceId: null,
					deviceName: null,
					recordTime: null,
					oilValue: 0,
					remark: null,
					submitter: null,
					confirmor: null,
					recordType: null,
					recordComments: null,
					userConfirmPwd: null,
					oilWay: '2',
					odoValue: null,
					odoTableValue: null,
					ohcValue: null,
					ohcTableValue: null,
					oilPrice: 0,
					measurePointId: null,
					oilSubType: null,
					submitterPassword: null
				},
				oilRecordRules: {
					orgId: [{
						required: true,
						message: '请选择单位',
						trigger: 'blur'
					}],
					deviceId: [{
						required: true,
						message: '请选择车辆',
						trigger: 'blur'
					}],
					oilPrice: [{
						required: true,
						message: '请填写油价格',
						trigger: 'blur'
					}],
					oilValue: [{
						required: true,
						message: '请填写加油量（1~500L）',
						trigger: 'blur'
					}],
					recordComments: [{
						required: true,
						message: '请填写加油人工号',
						trigger: 'blur'
					}],
					userConfirmPwd: [{
						required: true,
						message: '请填写加油人授权码',
						trigger: 'blur'
					}],
					submitter: [{
						required: true,
						message: '请填写操作人员工号',
						trigger: 'blur'
					}],
					submitterPassword: [{
						required: true,
						message: '请填写操作人员密码',
						trigger: 'blur'
					}]
				},
				oilSubTypeList: [],
				oilSubTypeDict: {
					"2001": [{
							id: "200101",
							name: "0#柴油"
						},
						{
							id: "200102",
							name: "-10#柴油"
						},
						{
							id: "200103",
							name: "-20#柴油"
						},
					],
					"2002": [{
							id: "200201",
							name: "92#汽油"
						},
						{
							id: "200202",
							name: "95#汽油"
						},
						{
							id: "200203",
							name: "98#汽油"
						},
					]
				},
				currentTime: new Date()
			}
		},
		methods: {
			onCompanySelected: function(e) {
				const selectedOrg = e[0];
				this.oilRecord.orgId = selectedOrg.value;
				this.oilRecord.orgName = selectedOrg.label;
				let that = this;
				loadOilDeviceList(selectedOrg.value, (res) => {
					const resJson = JSON.parse(res);
					if (resJson.success !== true) {
						uni.showToast({
							title: '没有找到用油设备',
							duration: 1000
						})
						return;
					}
					resJson.data.forEach((item, index, arr) => {
						that.oilDeviceList.push({
							value: item.id,
							label: item.description
						});
					});
				});
			},
			onDeviceSelected: function(e) {
				const selectedOrg = e[0];
				this.oilRecord.deviceId = selectedOrg.value;
				this.oilRecord.deviceName = selectedOrg.label;
			},
			onConfirmOilDate: function(e) {
				if (e.month < 10) {
					e.month = '0' + e.month;
				}
				if (e.day < 10) {
					e.day = '0' + e.day;
				}
				if (e.minute < 10) {
					e.minute = '0' + e.minute;
				}
				this.oilRecord.recordTime = e.year + '-' + e.month +
					'-' + e.day + ' ' + e.hour + ':' + e.minute + ':' + e.second;
			},
			onSelectOilType: function(text) {
				if (!this.oilRecord.deviceId) {
					uni.showToast({
						title: '请先选择用油设备',
						duration: 1000
					});
					return;
				}
				let oilType = text;
				if (text === '柴油') {
					oilType = 2001;
				} else if (text === '汽油') {
					oilType = 2002;
				} else {
					return;
				}
				this.oilSubTypeList = this.oilSubTypeDict[oilType];
				let that = this;
				checkOilMeasurePoint({
					oilType: oilType,
					deviceId: this.oilRecord.deviceId
				}, (res) => {
					const resJson = JSON.parse(res);
					if (resJson.success !== true || (resJson.success === true && resJson.data.length < 1)) {
						uni.showToast({
							title: text + '采集未添加，请联系后台管理员！',
							duration: 2000,
							icon: 'none'
						});
						return;
					}
					that.oilRecord.measurePointId = resJson.data[0].id;
				})
			},
			onSelectOilSubType: function(text) {
				let that = this;
				this.oilSubTypeList.filter((item, index, arr) => {
					if (item.name === text) {
						that.oilRecord.oilSubType = item.id;
					}
				})
			},
			scanQrCode: function() {
				let that = this;
				// 只允许通过相机扫码
				uni.scanCode({
					onlyFromCamera: true,
					success: function(res) {
						// console.log('条码类型：' + res.scanType);
						// console.log('条码内容：' + res.result);
						that.queryDeviceInfo(res.result);
					}
				});
			},
			queryDeviceInfo: function(assetCode) {
				if (!assetCode) {
					uni.showToast({
						title: '设备编码为空',
						duration: 1000
					});
					return;
				}
				let that = this;
				getDeviceInfo(assetCode, (res) => {
					const resJson = JSON.parse(res);
					if (resJson.data) {
						that.onCompanySelected([{
							value: resJson.data.orgId,
							label: resJson.data.orgName
						}]);
						that.onDeviceSelected([{
							value: resJson.data.deviceId,
							label: resJson.data.deviceName
						}]);
						// that.oilRecord.deviceId = resJson.data.deviceId;
						// that.oilRecord.deviceName = resJson.data.deviceName;
						// that.oilRecord.orgId = resJson.data.orgId;
						// that.oilRecord.orgName = resJson.data.orgName;
					}
				})
			},
			saveOilRecrod: function() {
				if (Number(this.oilRecord.oilValue) < 1) {
					uni.showToast({
						title: '必须填写加油量（单位：升）',
						duration: 1000
					})
					return;
				}

				let that = this;
				this.$refs.oilRecordForm.validate(valid => {
					if (valid) {
						checkUserAuth({
							oilUser: that.oilRecord.recordComments,
							userPwd: sha1(hex_md5(that.oilRecord.userConfirmPwd)),
							operator: that.oilRecord.submitter,
							operatorPwd: sha1(hex_md5(that.oilRecord.submitterPassword))
						}, (res) => {
							const resJson = JSON.parse(res);
							if (resJson.data < 1) {
								uni.showToast({
									title: '授权信息验证失败',
									duration: 2000,
									icon: 'error'
								})
								return;
							}
							that.doSaveOilRecord(that.oilRecord);
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			doSaveOilRecord: function(oilRecordInfo) {
				if (!oilRecordInfo) {
					uni.showToast({
						title: '信息不完整，请填写加油记录信息',
						duration: 1000,
						icon: 'error'
					})
					return;
				}
				let that = this;
				saveOilRecordData(oilRecordInfo, (res) => {
					// that.$refs.oilRecordForm.reset();
					uni.showToast({
						title: '加油记录提交成功！',
						duration: 2000,
						icon: 'success'
					});
					that.$refs.oilRecordForm.resetFields();

					that.lastOilRecord = {
						odoTableValue: null,
						ohcTableValue: null
					};
					that.oilRecord = {
						orgId: null,
						orgName: null,
						deviceId: null,
						deviceName: null,
						recordTime: null,
						oilValue: 0,
						remark: null,
						submitter: null,
						confirmor: null,
						recordType: null,
						recordComments: null,
						userConfirmPwd: null,
						oilWay: '2',
						odoValue: null,
						odoTableValue: null,
						ohcValue: null,
						ohcTableValue: null,
						oilPrice: 0,
						measurePointId: null,
						oilSubType: null,
						submitterPassword: null
					};
				});
			},
			loadOrgList: function() {
				let that = this;
				loadDeviceCompanyList((res) => {
					const resJson = JSON.parse(res);
					if (resJson.success !== true) {
						uni.showToast({
							title: '未获取到用油单位，错误：' + resJson.msg,
							duration: 1000

						});
						return;
					} else {
						if (resJson.data.length < 1) {
							uni.showToast({
								title: '单位列表为空',
								duration: 1000
							});
							return;
						}
						if (!resJson.data[0].children || resJson.data[0].children.length < 1) {
							uni.showToast({
								title: '用油单位列表为空',
								duration: 1000
							});
							return;
						}
						that.companyList = [];
						resJson.data[0].children.forEach((item, index, arr) => {
							that.companyList.push({
								value: item.id,
								label: item.deptName
							});
						});
						// console.log(that.companyList);
					}
				});
			}
		},
		created() {
			this.loadOrgList();
			this.onConfirmOilDate({
				year: this.currentTime.getYear() + 1900,
				month: this.currentTime.getMonth() + 1,
				day: this.currentTime.getDay(),
				hour: this.currentTime.getHours(),
				minute: this.currentTime.getMinutes(),
				second: '00'
			});
		},
		onReady() {
			this.$refs.oilRecordForm.setRules(this.oilRecordRules);
		}
	}
</script>
<style scoped lang="scss">
	.wrap {
		padding: 30rpx;
	}

	.agreement {
		display: flex;
		align-items: center;
		margin: 40rpx 0;

		.agreement-text {
			padding-left: 8rpx;
			color: $u-tips-color;
		}
	}

	.info-panel {
		height: 60rpx;
		line-height: 60rpx;
		font-size: 24;
		font-weight: bold;
		border-left: 4px solid var(--theme-color, #333);
		padding-left: 20rpx;
		margin-left: -10rpx;
		background-color: #FFFFFF;
	}
</style>
